package config

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"partyus_app/global"
	"partyus_app/models"
	"time"
)

// InitDB 初始化数据库连接
func InitDB() {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second, //慢sql阈值
			LogLevel:      logger.Info, //级别
			Colorful:      true,
		},
	)
	// 从全局配置中获取数据库配置
	dsn := GlobalConfig.Database.DSN
	maxIdleConns := GlobalConfig.Database.MaxIdleConns
	maxOpenConns := GlobalConfig.Database.MaxOpenConns

	// 初始化 GORM
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		log.Fatalf("failed to connect to database: %w", err)
	}

	// 配置连接池
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatalf("failed to get database instance: %w", err)
	}
	sqlDB.SetMaxIdleConns(maxIdleConns)
	sqlDB.SetMaxOpenConns(maxOpenConns)

	// 赋值给全局变量
	global.Db = db
	log.Println("Database connection initialized successfully")

	// 在初始化数据库的函数中
	if err := global.Db.AutoMigrate(&models.User{}); err != nil {
		log.Fatalf("failed to auto migrate: %v", err)
	}
	if err := global.Db.AutoMigrate(&models.Post{}); err != nil {
		log.Fatalf("failed to auto migrate: %v", err)
	}
}
